﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Yonyou.U8.QuickImport
{
   
    public partial class ListLog : Form
    {
        private Context _Context;
        private string strSQL;
        private int intQueryType;
        private DataTable LogList;

        public ListLog(Context context)
        {
            _Context = context;
            InitializeComponent();
            this.Load += ListLog_Load;
            cmdCancel.Click+= cmdCancel_Click;
            cmdQuery.Click+= cmdQuery_Click;
            cmdPrint.Click+= cmdPrint_Click;
            cmdDelete.Click+= cmdDelete_Click;
            logGrid.CellDoubleClick += logGrid_CellDoubleClick;
            this.gridContainer.ClientSizeChanged += new System.EventHandler(gridContainer_ClientSizeChanged);
        }

        protected Context QIContext
        {
            get
            {
                return _Context;
            }
        }

        private void ListLog_Load(object sender, EventArgs e)
        {
            InitialList();
            float num = (float)Screen.PrimaryScreen.Bounds.Width / 800f;
            logGrid.Width = (int)((float)logGrid.Width * num);
        }

        public void SetQueryXML(string strQuery, int QueryType)
        {
            strSQL = strQuery;
            intQueryType = QueryType;
            InitialList();
        }

        private void InitialList()
        {
            try
            {
                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Context.QIPath + "\\log\\loglist.mdb;";
                OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
                oleDbConnection.Open();
                string text = "SELECT 编号 as num,importtime,type,name,filename,succeeded,failed,username,token,importtype,deletetag FROM log ";
                OleDbCommand selectCommand = new OleDbCommand(text + strSQL, oleDbConnection);
                OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter();
                oleDbDataAdapter.SelectCommand = selectCommand;
                DataSet dataSet = new DataSet();
                dataSet.DataSetName = "ufinterface";
                oleDbDataAdapter.Fill(dataSet, "LogList");
                LogList = dataSet.Tables["LogList"];
                foreach (DataRow row in LogList.Rows)
                {
                    row["importtype"] = ConvertStrValue(row["importtype"].ToString());
                }
                logGrid.DataSource = LogList.DefaultView;
                oleDbConnection.Close();
                if (intQueryType == 2)
                {
                    new ChoseModel();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cmdQuery_Click(object sender, EventArgs e)
        {
            TabPage tapPage;
            if (QIContext.CheckTab("tpImportLog", out tapPage))
            {
                QIContext.TabContainer.SelectedTab = tapPage;
            }
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            TabPage tapPage;
            if (QIContext.CheckTab("tpListLog", out tapPage) && tapPage != null)
            {
                QIContext.TabContainer.TabPages.Remove(tapPage);
            }
            TabPage tabPage = base.Tag as TabPage;
            if (tabPage != null)
            {
                QIContext.TabContainer.SelectedTab = tabPage;
            }
        }

        private void cmdPrint_Click(object sender, EventArgs e)
        {
            PrintDocument printDocument = new PrintDocument();
            printDocument.PrintPage += printDoc_PrintPage;
            printDialog1.AllowSomePages = true;
            printDialog1.AllowCurrentPage = true;
            printDialog1.AllowPrintToFile = true;
            printDialog1.AllowSelection = true;
            printDialog1.ShowHelp = true;
            printDialog1.Document = printDocument;
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument.Print();
            }
        }

        private void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
        }

        private void cmdDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (logGrid.SelectedRows.Count <= 0)
                {
                    return;
                }
                int index = logGrid.SelectedRows[0].Index;
                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Context.QIPath + "\\log\\loglist.mdb;";
                OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
                oleDbConnection.Open();
                OleDbCommand oleDbCommand = new OleDbCommand("delete FROM log where 编号=" + LogList.Rows[logGrid.SelectedRows[0].Index].ItemArray[0].ToString(), oleDbConnection);
                oleDbCommand.ExecuteNonQuery();
                oleDbConnection.Close();
                try
                {
                    string path = LogList.Rows[logGrid.SelectedRows[0].Index].ItemArray[4].ToString();
                    File.Delete(path);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                intQueryType = 1;
                InitialList();
                if (logGrid.Rows.Count > 1)
                {
                    if (index < logGrid.Rows.Count)
                    {
                        logGrid.Rows[index].Selected = true;
                    }
                    else
                    {
                        logGrid.Rows[logGrid.Rows.Count - 1].Selected = true;
                    }
                    logGrid.FirstDisplayedScrollingRowIndex = logGrid.SelectedRows[0].Index;
                }
            }
            catch (Exception ex2)
            {
                MessageBox.Show(ex2.Message);
            }
        }

        private void ListLog_Closing(object sender, CancelEventArgs e)
        {
        }

        private void cmdDeleteData_Click(object sender, EventArgs e)
        {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Context.QIPath + "\\log\\loglist.mdb;";
            OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
            oleDbConnection.Open();
            OleDbCommand oleDbCommand = new OleDbCommand("select * FROM log where 编号=" + LogList.Rows[logGrid.SelectedRows[0].Index].ItemArray[0].ToString(), oleDbConnection);
            OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader();
            string innerText = oleDbDataReader["type"].ToString();
            string innerText2 = oleDbDataReader["name"].ToString();
            string innerText3 = oleDbDataReader["filename"].ToString();
            oleDbDataReader.Close();
            oleDbConnection.Close();
            string xml = "<?xml version=\"1.0\" ?><data><class id='' name=''/><import type='' logfilepath=''alerttype=''/></data>";
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("//class");
            XmlNode xmlNode2 = xmlDocument.CreateElement("", "menu", "");
            XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("id");
            xmlAttribute.InnerText = innerText;
            XmlAttribute xmlAttribute2 = xmlDocument.CreateAttribute("name");
            xmlAttribute2.InnerText = innerText2;
            XmlAttribute xmlAttribute3 = xmlDocument.CreateAttribute("filename");
            xmlAttribute3.InnerText = innerText3;
            xmlNode2.Attributes.Append(xmlAttribute);
            xmlNode2.Attributes.Append(xmlAttribute2);
            xmlNode2.Attributes.Append(xmlAttribute3);
            xmlNode.AppendChild(xmlNode2);
            XmlDocument xmlDocument2 = new XmlDocument();
            xmlDocument2.Load(Context.QIPath + "\\ImportStrategy\\ImportParameter.xml");
            XmlNode xmlNode3 = xmlDocument.SelectSingleNode("//import");
            xmlNode3.Attributes.Item(0).Value = "3";
            xmlNode3.Attributes.Item(1).Value = xmlDocument2.DocumentElement.FirstChild.Attributes.Item(1).Value;
            xmlNode3.Attributes.Item(2).Value = xmlDocument2.DocumentElement.FirstChild.Attributes.Item(2).Value;
        }

        private void logGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.RowIndex <= logGrid.Rows.Count - 1 && e.ColumnIndex >= 0 && e.ColumnIndex <= logGrid.Columns.Count - 1)
            {
                string text = LogList.Rows[e.RowIndex].ItemArray[4].ToString();
                if (string.Compare(Path.GetExtension(text), ".txt", true) == 0 || string.Compare(Path.GetExtension(text), ".csv", true) == 0)
                {
                    Process.Start("notepad", text);
                    return;
                }
                OpenLogFile openLogFile = new OpenLogFile(LogList.Rows[e.RowIndex].ItemArray[4].ToString());
                openLogFile.OpenLog(QIContext);
            }
        }

        private void gridContainer_ClientSizeChanged(object sender, EventArgs e)
        {
            logGrid.Height = gridContainer.ClientSize.Height;
            logGrid.Width = gridContainer.ClientSize.Width - logGrid.Location.X;
        }

        private string ConvertStrValue(string strValue)
        {
            switch (strValue)
            {
                case "True":
                    return "是";
                case "False":
                    return "否";
                case "add":
                    return "追加";
                case "edit":
                    return "覆盖";
                case "delete":
                    return "删除";
                case "empty":
                    return "清空";
                default:
                    return strValue;
            }
        }

    }
}
